from django.shortcuts import render,HttpResponse
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django.core.cache import cache
from . import restful
def index(request):
    return render(request,'log.html')
def send_sms(phone, code):
    # 这是阿里云短信接口密钥
    client = AcsClient('LTAIEx3Gbdbceg2C', 'MsCoWUm3x2iXaIcvtqhQLi9yj6nHxX', 'cn-hangzhou')
    code = "{'code':%s}" % (code)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')
    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', '北网实训组')
    request.add_query_param('TemplateCode', 'SMS_165745016')
    request.add_query_param('TemplateParam', code)
    response = client.do_action(request)
    print(str(response, encoding='utf-8'))
    return str(response, encoding='utf-8')

def get_code(n=6, alpha=True):
    s = ''  # 创建字符串变量,存储生成的验证码
    for i in range(n):  # 通过for循环控制验证码位数
        num = random.randint(0, 9)  # 生成随机数字0-9
        if alpha:  # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False
            upper_alpha = chr(random.randint(65, 90))
            lower_alpha = chr(random.randint(97, 122))
            num = random.choice([num, upper_alpha, lower_alpha])
        s = s + str(num)
    return s

def sms_send(request):
    phone=request.GET.get('phone')
    code=get_code(6,False)
    cache.set(phone,code,30*60)
    print('判断缓存中是否有，',cache.has_key(phone))
    print('获取Redis的验证码',cache.get(phone))
    print('----------------------------')
    print(phone)
    print(type(phone))
    print('------------------------------')
    result = send_sms(phone, code)
    return HttpResponse(result)

def sms_check(request):
    phone=request.GET.get('phone')
    code=request.GET.get('code')
    print('缓存中是否包含:',cache.has_key(phone))
    print('取值:',cache.get(phone))
    cache_code = cache.get(phone)
    if cache_code==code:
        print('ok')
        # return HttpResponse(json.dumps({'result':'OK'}))
        return restful.ok('OK',data=None)
    else:
        print('bo')
        # return HttpResponse(json.dumps({'result':'False'}))
        return restful.params_error('验证码错误',data=None)


if __name__ == '__main__':
    # 调用下发短信方法
    send_sms('18335828842', get_code(6, False))
    print(get_code(6, False))  # 打印6位数字验证码
    print(get_code(6, True))   # 打印6位数字字母混合验证码
    print(get_code(4, False))  # 打印4位数字验证码
    print(get_code(4, True))   # 打印4位数字字母混合验证码


